const { Article } = require('../model/article')
const { User } = require('../model/user')
const { Category } = require('../model/categories')

exports.getAll = async (req, res, next) => {
  try {
    // 检测是否存在 文章/状态 筛选参数
    const { categories, status } = req.query
    let data
    if (categories || status) {
      data = await Article.find(req.query)
    } else {
      data = await Article.find()
    }
    return res.status(200).json({
      code: 200,
      data,
      total: data.length,
      msg: '查询成功'
    })
  } catch (err) {
    next(err)
  }
}

// 添加文章
exports.create = async (req, res, next) => {
  try {
    console.log(req.body)
    console.log(req.userData._id)
    let obj = Object.assign(req.body, { author: req.userData._id })
    let article = new Article(obj)
    await article.save()
    return res.status(200).json({
      code: 200,
      message: '添加成功'
    })
  } catch (err) {
    next(err)
  }
}

// 获取文章
exports.get = async (req, res, next) => {
  try {
    // 获取动态路由id
    let id = req.params.aid
    // 根据id获取文章
    let data
    try {
      data = await Article.findById(id).populate('category', 'name').populate('author', 'name')
    } catch (err) {
      return res.status(200).json({
        code: 400,
        msg: '查询失败'
      })
    }
    res.status(200).json({
      code: 200,
      msg: '查询成功',
      data: data
    })
  } catch (err) {
    next(err)
  }
}

// 修改文章
exports.update = async (req, res, next) => {
  try {
    let id = req.params.aid
    if (!id) {
      return res.status(400).json({
        code: 400,
        msg: '缺少参数aid'
      })
    }
    const data = await Article.findByIdAndUpdate(id, req.body, { new: true })
    if (data) {
      res.status(200).json({
        code: 200,
        msg: '更新成功',
        data: data
      })
    } else {
      res.status(500).json({
        code: 500,
        msg: '更新失败'
      })
    }
  } catch (err) {
    next(err)
  }
}

// 删除文章
exports.delete = async (req, res, next) => {
  try {
    // 获取id
    let id = req.params.aid
    if (!id) {
      return res.status(400).json({
        code: 400,
        msg: '缺少参数aid'
      })
    }
    let data
    try {
      data = await Article.findByIdAndDelete(id)
    } catch (err) {
      return res.status(500).json({
        code: 500,
        msg: '删除失败'
      })
    }
    return res.status(200).json({
      code: 200,
      msg: '删除成功'
    })
  } catch (err) {
    next(err)
  }
}
